All files / src/app/api/transfers/[id]/data route.ts

87.5% Statements 21/24
76.92% Branches 20/26
100% Functions 1/1
91.3% Lines 21/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91                      1x                                 15x 15x   15x 15x 15x 1x             14x 14x                     14x 15x 1x                 13x 13x 6x     15x                     7x 7x 7x 7x 7x            
import { NextRequest, NextResponse } from "next/server";
import { edcClient } from "@/lib/edc";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { seesPatientIdentity } from "@/lib/patient-identity";
import {
  isPlainId,
  pseudonymiseFhir,
  pullTransferData,
  TransferDataError,
} from "@/lib/transfer-data";
 
export const dynamic = "force-dynamic";
 
/**
 * GET /api/transfers/[id]/data?participantId=<consumer ctx> — the data a
 * STARTED HttpData-PULL transfer gives access to (#876).
 *
 * A transfer stays STARTED while its access is open; nothing on the transfer
 * page read the data, so every real transfer showed "in progress" for good.
 * This asks the consumer's siglet for the flow's token and calls the
 * provider's data plane with it (lib/transfer-data.ts). The token stays on the
 * server. Patient resources come back pseudonymised for roles that do not see
 * identity (#475).
 */
export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  const auth = await requireAuth();
  Iif (isAuthError(auth)) return auth;
 
  const { id } = await params;
  const participantId = req.nextUrl.searchParams.get("participantId") || "";
  if (!isPlainId(participantId) || !isPlainId(id)) {
    return NextResponse.json(
      { error: "participantId and a transfer id are required" },
      { status: 400 },
    );
  }
 
  let transfer: Record<string, unknown>;
  try {
    transfer = await edcClient.management<Record<string, unknown>>(
      `/v5/participants/${participantId}/transferprocesses/${id}`,
    );
  } catch (err) {
    console.error(`Transfer ${id} not readable:`, err);
    return NextResponse.json(
      { error: "Not found", detail: "The connector has no such transfer" },
      { status: 404 },
    );
  }
 
  const state = String(transfer.state ?? "");
  if (state !== "STARTED") {
    return NextResponse.json(
      {
        error: `The transfer is ${state || "in no known state"}, not STARTED`,
        state,
      },
      { status: 409 },
    );
  }
 
  try {
    const pulled = await pullTransferData(participantId, id, transfer);
    const data = seesPatientIdentity(auth.session.roles)
      ? pulled.data
      : pseudonymiseFhir(pulled.data);
    return NextResponse.json({
      transferId: id,
      assetId: transfer.assetId ?? "",
      contractId: transfer.contractId ?? "",
      contentType: pulled.contentType,
      bytes: pulled.bytes,
      truncated: pulled.truncated,
      fetchedAt: new Date().toISOString(),
      data,
    });
  } catch (err) {
    const step = err instanceof TransferDataError ? err.step : "data";
    const expired = err instanceof TransferDataError && err.expired;
    const detail = err instanceof Error ? err.message : String(err);
    console.error(`Pulling the data of transfer ${id} failed at ${step}:`, err);
    return NextResponse.json(
      { error: "Failed to fetch the transfer's data", step, detail, expired },
      { status: 502 },
    );
  }
}